<template>
  <div class="app-container">
    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button
            type="danger"
            :disabled="selectedIds.length === 0"
            icon="delete"
            @click="() => handleDelete()"
          >
            删除
          </el-button>
          <el-button type="success" icon="refresh" @click="handleOpenDialog">手动触发</el-button>
          <el-button type="primary" icon="search" @click="handleCheckEvent">检查事件</el-button>
          <el-button type="warning" icon="plus" @click="handleTriggerEvent">触发新事件</el-button>
        </div>
        <div class="data-table__toolbar--filters">
          <el-radio-group v-model="reportType" @change="handleReportTypeChange">
            <el-radio-button value="all">全部</el-radio-button>
            <el-radio-button value="SOE">SOE</el-radio-button>
            <el-radio-button value="SOCILLOGRAPHY">SOCILLOGRAPHY</el-radio-button>
          </el-radio-group>
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleDateRangeChange"
          />
        </div>
      </div>
      <!-- style="min-width: 700px" -->
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="filteredTableData"
        highlight-current-row
        border
        fit
        class="data-table__content"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          v-for="(col, index) in coreColumns"
          :key="index"
          :prop="col.key"
          :label="col.label"
          :minWidth="col.width"
          align="left"
          :fixed="col.fixed || false"
        >
          <template #default="{ row }">
            <span>{{ getValueByKey(row, col.key) }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="270">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              icon="view"
              @click="() => openDetailDrawer(scope.row)"
            >
              详情
            </el-button>
            <!-- click 点击跳转到录波 -->
            <el-button type="primary" size="small" link icon="view" @click="goToWaveChart">
              录波
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              icon="download"
              @click="() => handleDownload(scope.row.faultId)"
            >
              下载
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              icon="delete"
              @click="() => handleDelete(scope.row.faultId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <offset-pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:offset="queryParams.offset"
        v-model:limit="queryParams.limit"
        @pagination="fetchData"
      />
    </el-card>
    <el-drawer v-model="drawerVisible" title="报告详情" size="40%" :with-header="true">
      <el-descriptions :column="1" border>
        <!-- <el-descriptions-item label="故障序号">
          {{ selectedRow?.faultId }}
        </el-descriptions-item> -->
        <el-descriptions-item label="报告名称">
          {{ selectedRow?.reportName }}
        </el-descriptions-item>
        <!-- <el-descriptions-item label="故障时间">
          {{ selectedRow?.faultTime }}
        </el-descriptions-item> -->
        <el-descriptions-item label="故障开始时间">
          {{ selectedRow?.faultStartTime }}
        </el-descriptions-item>
        <el-descriptions-item label="故障持续时间">
          {{ selectedRow?.faultKeepingTime }}
        </el-descriptions-item>

        <!-- 设备信息 -->
        <el-descriptions-item label="设备信息">
          <el-collapse>
            <el-collapse-item>
              <template #title>
                <span class="font-bold">设备基本信息</span>
              </template>
              <el-descriptions :column="1" border>
                <el-descriptions-item
                  v-for="(info, index) in selectedRow?.deviceInfo"
                  :key="index"
                  :label="info.name"
                >
                  {{ info.value }}
                </el-descriptions-item>
              </el-descriptions>
            </el-collapse-item>
          </el-collapse>
        </el-descriptions-item>

        <!-- 故障信息 -->
        <el-descriptions-item label="故障信息">
          <el-collapse>
            <el-collapse-item v-for="(trip, tripIndex) in selectedRow?.tripInfo" :key="tripIndex">
              <template #title>
                <span class="font-bold">{{ trip.name }}</span>
                <span class="ml-2 text-gray-500">{{ trip.time }}</span>
              </template>
              <el-descriptions :column="1" border>
                <template v-if="Array.isArray(trip.FaultInfo)">
                  <el-descriptions-item
                    v-for="(info, infoIndex) in trip.FaultInfo"
                    :key="infoIndex"
                    :label="getInfCodeAndText(info.name)"
                  >
                    {{ getInfCodeAndText(info.value) }}
                  </el-descriptions-item>
                </template>
                <template v-else>
                  <el-descriptions-item :label="getInfCodeAndText(trip.FaultInfo.name)">
                    {{ getInfCodeAndText(trip.FaultInfo.value) }}
                  </el-descriptions-item>
                </template>
              </el-descriptions>
            </el-collapse-item>
          </el-collapse>
        </el-descriptions-item>

        <!-- 数字状态信息 -->
        <el-descriptions-item label="数字状态信息">
          <el-collapse>
            <el-collapse-item>
              <template #title>
                <span class="font-bold">
                  数字状态 ({{ selectedRow?.digitalStatus?.length || 0 }} 项)
                </span>
              </template>
              <el-descriptions :column="2" border>
                <el-descriptions-item
                  v-for="(status, index) in selectedRow?.digitalStatus"
                  :key="index"
                  :label="status.name"
                >
                  {{ status.value }}
                </el-descriptions-item>
              </el-descriptions>
            </el-collapse-item>
          </el-collapse>
        </el-descriptions-item>

        <!-- 数字事件信息 -->
        <el-descriptions-item label="数字事件信息">
          <el-collapse>
            <el-collapse-item>
              <template #title>
                <span class="font-bold">
                  数字事件 ({{ selectedRow?.digitalEvent?.length || 0 }} 项)
                </span>
              </template>
              <el-descriptions :column="1" border>
                <el-descriptions-item
                  v-for="(event, index) in selectedRow?.digitalEvent"
                  :key="index"
                  :label="`${event.time} - ${event.name}`"
                >
                  {{ event.value }}
                </el-descriptions-item>
              </el-descriptions>
            </el-collapse-item>
          </el-collapse>
        </el-descriptions-item>

        <!-- 系统设置值信息 -->
        <el-descriptions-item label="系统设置值信息">
          <el-collapse>
            <el-collapse-item>
              <template #title>
                <span class="font-bold">
                  系统设置值 ({{ selectedRow?.sysSettingValue?.length || 0 }} 项)
                </span>
              </template>
              <el-descriptions :column="1" border>
                <el-descriptions-item
                  v-for="(setting, index) in selectedRow?.sysSettingValue"
                  :key="index"
                  :label="setting.name"
                >
                  {{ setting.value }} {{ setting.unit }}
                </el-descriptions-item>
              </el-descriptions>
            </el-collapse-item>
          </el-collapse>
        </el-descriptions-item>

        <!-- 设置值信息 -->
        <el-descriptions-item label="设置值信息">
          <el-collapse>
            <el-collapse-item>
              <template #title>
                <span class="font-bold">
                  设置值 ({{ selectedRow?.settingValue?.length || 0 }} 项)
                </span>
              </template>
              <el-descriptions :column="1" border>
                <el-descriptions-item
                  v-for="(setting, index) in selectedRow?.settingValue"
                  :key="index"
                  :label="setting.name"
                >
                  {{ setting.value }} {{ setting.unit }}
                </el-descriptions-item>
              </el-descriptions>
            </el-collapse-item>
          </el-collapse>
        </el-descriptions-item>

        <!-- 继电器使能信息 -->
        <el-descriptions-item label="继电器使能信息">
          <el-collapse>
            <el-collapse-item>
              <template #title>
                <span class="font-bold">
                  继电器使能 ({{ selectedRow?.relayEnaInfo?.length || 0 }} 项)
                </span>
              </template>
              <el-descriptions :column="2" border>
                <el-descriptions-item
                  v-for="(relay, index) in selectedRow?.relayEnaInfo"
                  :key="index"
                  :label="relay.name"
                >
                  {{ relay.value }}
                </el-descriptions-item>
              </el-descriptions>
            </el-collapse-item>
          </el-collapse>
        </el-descriptions-item>
      </el-descriptions>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { mockReportListFromHdr, ReportItem } from "@/composables/useParseHdrFile";
import { ref, computed, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";

// 只展示核心字段
const coreColumns = [
  // { key: "faultId", label: "故障序号", width: 100, fixed: true },
  { key: "reportName", label: "报告名称", width: 420, fixed: true },
  { key: "reportType", label: "报告类型", width: 100, fixed: true },
  { key: "faultStartTime", label: "故障开始时间", width: 420, fixed: true },
  { key: "faultKeepingTime", label: "故障持续时间", width: 170, fixed: true },
  // { key: "faultTime", label: "故障时间", width: 420, fixed: true },
];

const loading = ref(false);
const selectedIds = ref<number[]>([]);
const queryParams = reactive({
  offset: 0,
  limit: 10,
});
const total = ref(0);
const allData = ref<ReportItem[]>([]);

// 新增的状态变量
const reportType = ref("all");
const dateRange = ref<[string, string] | undefined>(undefined);

const router = useRouter();

// 过滤后的表格数据
const filteredTableData = computed(() => {
  let filtered = [...allData.value];

  // 根据报告类型过滤
  if (reportType.value !== "all") {
    filtered = filtered.filter((item) => {
      const mainTrip = item.tripInfo[0];
      return mainTrip?.name === reportType.value;
    });
  }

  // 根据时间范围过滤
  if (dateRange.value) {
    const [startDate, endDate] = dateRange.value;
    filtered = filtered.filter((item) => {
      // const faultTime = new Date(item.faultTime).getTime();
      // 将空格替换为 'T'，最后一个冒号替换为 '.' 形成 ISO 格式
      const isoTime = item.faultTime.replace(" ", "T").replace(/:(\d+)$/, ".$1"); // 将末尾的 ":822" 改为 ".822"
      // 直接解析为时间戳
      const faultTime = new Date(isoTime).getTime();
      return faultTime >= new Date(startDate).getTime() && faultTime <= new Date(endDate).getTime();
    });
  }

  // 分页处理
  const start = queryParams.offset;
  const end = start + queryParams.limit;
  return filtered.slice(start, end);
});

function getValueByKey(row: any, key: string) {
  return key.split(".").reduce((obj, k) => obj?.[k], row) ?? "-";
}

function handleSelectionChange(selection: any[]) {
  selectedIds.value = selection.map((item: any) => item.faultId);
}

function handleDelete(rowId?: number) {
  const rowIds = rowId ? [rowId] : selectedIds.value;
  if (!rowIds.length) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      loading.value = true;
      setTimeout(() => {
        allData.value = allData.value.filter((item) => !rowIds.includes(item.faultId));
        selectedIds.value = [];
        loading.value = false;
        total.value = allData.value.length;
        ElMessage.success("删除成功");
      }, 500);
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
}

function handleDownload(rowId: number) {
  const row = allData.value.find((item) => item.faultId === rowId);
  if (!row) return;
  const blob = new Blob([JSON.stringify(row, null, 2)], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `report_${rowId}.json`;
  a.click();
  URL.revokeObjectURL(url);
  ElMessage.success(`已下载: report_${rowId}.json`);
}

function handleOpenDialog() {
  ElMessage.info("新增功能开发中");
}

function handleCheckEvent() {
  ElMessage.info("检查事件功能开发中");
}

function handleTriggerEvent() {
  ElMessage.info("触发新事件功能开发中");
}

function handleReportTypeChange() {
  queryParams.offset = 0;
  fetchData();
}

function handleDateRangeChange() {
  queryParams.offset = 0;
  fetchData();
}

function fetchData() {
  // 这里可对接后端分页
}

// 详情抽屉相关
const drawerVisible = ref(false);
const selectedRow = ref<ReportItem | null>(null);
function openDetailDrawer(row: ReportItem) {
  selectedRow.value = row;
  drawerVisible.value = true;
}

function goToWaveChart() {
  router.push("/chart/wave-chart");
}

// 读取 hdr 文件并模拟多条数据
async function loadHdrReports() {
  // console.log("loadHdrReports");
  loading.value = true;
  try {
    const hdrRes = await fetch("/wave-data/JMXZLP215_RCD_00020_20250613_090622_822_f.hdr");
    const buffer = await hdrRes.arrayBuffer();
    // @ts-ignore
    const decoder = new TextDecoder("utf-8");
    const hdrContent = decoder.decode(buffer);
    // console.log(hdrContent);
    allData.value = mockReportListFromHdr(
      hdrContent,
      3,
      "JMXZLP215_RCD_00020_20250613_090622_822_f"
    ); // 模拟3条
    total.value = allData.value.length;
  } catch {
    ElMessage.error("故障报告文件加载失败");
  } finally {
    loading.value = false;
  }
}

// 新增：优先显示 @_InfCode 和 #text 的辅助方法
function getInfCodeAndText(obj: any): string {
  if (!obj) return "";
  if (typeof obj === "object") {
    const code = obj["@_InfCode"];
    const text = obj["#text"];
    if (code && text) return `${text} (InfCode:${code})`;
    if (text) return text;
    if (code) return `(InfCode:${code})`;
    return "";
  }
  return typeof obj === "string" ? obj : JSON.stringify(obj);
}

onMounted(() => {
  console.log("onMounted");
  loadHdrReports();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 24px;
}
.data-table__toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  flex-wrap: wrap;
  gap: 12px;
}
.data-table__toolbar--actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}
.data-table__toolbar--filters {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}
.data-table__content {
  min-width: 700px;
  margin-bottom: 16px;
}
.font-bold {
  font-weight: bold;
}
.ml-2 {
  margin-left: 0.5rem;
}
.text-gray-500 {
  color: #6b7280;
}
</style>
